package com.yuan.rest.controller.admin;


import com.yuan.rest.entrity.SysUser;
import com.yuan.rest.repository.SysUserRepository;
import com.yuan.rest.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @Auther: SiYuan
 * @Date: 2019/3/4 16:01
 * @Description:
 */

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    SysUserRepository sysUserRepository;

    @GetMapping("/list")
    public String userList() {
        return "admin/user_list";
    }


    /***
     *  获取用户列表  layUi 的表格数据
     * @param
     * @return
     */
    @GetMapping("/users")
    @ResponseBody
    public Result getUserList() {
        Result result = new Result();
//        if (name!=null){
//            SysUser sysUser = new SysUser();
//            sysUser.setUsername(name);
//            Example<SysUser> sysUserExample = Example.of(sysUser);
//            Optional<SysUser> one = sysUserRepository.findOne(sysUserExample);
//            result.put("count",1 );
//            result.put("data", one);
//        }else {
            result.put("count", sysUserRepository.findAll().size());
            result.put("data", sysUserRepository.findAll());
            return result;
//        }
//        return result;

    }

    /**
     * 添加用户
     * @param
     * @return
     */
//    @PostMapping("add")
//    @ResponseBody
//    public Result addUser(@RequestBody SysUser sysUser) {
//        SysUser save = sysUserRepository.save(sysUser);
//        return Result.ok().put("data",save);
//
//    }

    /**
     * 添加用户
     * @param
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public Result updateUser(@RequestBody SysUser sysUser) {
        Optional<SysUser> count= sysUserRepository.findById(sysUser.getUserId());
        if (count!=null){
            return Result.error();
        } else{
            SysUser save = sysUserRepository.save(sysUser);
            return Result.ok().put("data",save);
        }

    }



    /***
     *  删除用户
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    @ResponseBody
    public Result deletUser(@PathVariable long id) {

        Optional<SysUser> count= sysUserRepository.findById(id);
        if (count!=null){
            return Result.error();
        } else{
            sysUserRepository.deleteById(id);
            return Result.ok();
        }
    }


    /***
     * 根据用户名查询用户
     *
     */
    @GetMapping("{id}")
    @ResponseBody
    public Result getUserInfo(@PathVariable long id){
        Optional<SysUser> byId = sysUserRepository.findById(id);
        return Result.ok().put("data",byId);
    }


}
